<template>
    <div class="xiaoqu">
        <div>
        </div>
        <div class="xiaoqu-content">
            <div class="searchBox">
                <div class="searchLi">
                    <span class="xiaoquName">标题名称：</span>
                    <input type="text" autocomplete="off" v-model="searchContent.name">
                </div>
                <div class="searchLi">
                    <span>创建时间：</span>
                    <el-date-picker v-model="searchContent.time" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </div>
                <div class="searchBtn">
                    <el-button type="primary" @click="searchClick">搜索</el-button>
                </div>
            </div>
            <div class="addXiaoquBtn">
                <el-button type="text" @click="addXiaoqu" class="addBtn">新增公益信息</el-button>
                <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="80%">
                    <el-form :model="form">
                        <el-form-item label="公益标题" :label-width="formLabelWidth">
                            <el-input v-model="form.name" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="图片" :label-width="formLabelWidth">
                            <el-upload  v-if="dialogFormVisible" name="file" action="http://localhost:8080/free/upload"
                                list-type="picture-card" :file-list="uploadImageList" :auto-upload="true"
                                :on-success="uploadImg">
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{ file }">
                                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                    <span class="el-upload-list__item-actions">
                                        <span class="el-upload-list__item-preview"
                                            @click="handlePictureCardPreview(file)">
                                            <i class="el-icon-zoom-in"></i>
                                        </span>
                                        <span v-if="!disabled" class="el-upload-list__item-delete"
                                            @click="handleDownload(file)">
                                            <i class="el-icon-download"></i>
                                        </span>
                                        <span v-if="!disabled" class="el-upload-list__item-delete"
                                            @click="handleRemove(file)">
                                            <i class="el-icon-delete"></i>
                                        </span>
                                    </span>
                                </div>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="" />
                            </el-dialog>
                        </el-form-item>
                        <el-form-item label="公益简介" :label-width="formLabelWidth">
                            <el-input v-model="form.simplyintroduce" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="公益内容" :label-width="formLabelWidth">
                            <quill-editor class="editor" v-model="form.text" ref="myQuillEditor" :options="editorOption"
                                @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
                                @change="onEditorChange($event)" style="height: 300px">
                            </quill-editor>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="cancel">取 消</el-button>
                        <el-button @click="save">保 存</el-button>
                    </div>
                </el-dialog>
            </div>
            <div class="xiaoqu-table">
                <el-table :data="tableData" border :cell-style="{ 'text-align': 'center' }"
                    :header-cell-style="{ background: '#1890ff', color: '#ffffff', 'text-align': 'center' }">
                    <el-table-column prop="id" label="Id">
                    </el-table-column>
                    <el-table-column prop="name" label="公益标题">
                    </el-table-column>
                    <el-table-column label="图片">
                        <template slot-scope="scope">
                            <el-image style="width: 100px; height: 100px"
                                :src="'http://localhost:8080/free/download?filename=' + scope.row.picture"
                                fit="fill">
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="simplyintroduce" label="公益简介">
                    </el-table-column>
                    <el-table-column prop="text" label="公益内容">
                        <template slot-scope="scope">
                            <div v-html="scope.row.text"></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createtime" label="创建时间">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button @click="editClick(scope.row)" type="text" size="small">编辑公益信息</el-button>
                            <el-button @click="deleteClick(scope.row.id)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页处理 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[5, 10, 20, 30, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>


export default {
    name: "GongyiComponent",
    data() {
        return {
            //上传图片列表
            uploadImageList: [],
            // isEditing: false, // 用于区分是新增还是编辑模式
            editorOption: {},
            //上传文件所需
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,

            value1: '',
            input: '',
            dialogFormVisible: false,
            dialogTitle: '',//对话框标题
            form: {
                id: '',
                name: '',
                picture: '',
                simplyintroduce: '',
                text: '',
                createtime: ''
            },
            tableData: [],
            tableData2: [],
            addressAll: [],   //省市区
            address: [], //你选择的地址
            formLabelWidth: '120px',
            //查看关联门店里的搜索数据
            association: false,
            checkBtn2: {
                villageName2: "",
                pageNum: 1,
                pageSize: 10,
            },
            addAssociation: false,
            checkBtn3: {
                villageName3: "",
            },
            //搜索框数据对象
            searchContent: {
                name: "",
                time: [],
            },
            xiaoquID: "",
            tableData3: [],
            row: {},      // 全局row 把scope.row赋给它
            allId: -1,   //全局id用来在新增和修改是做判断
            //分页
            currentPage: 1, // 当前页数
            pageSize: 5, // 每页条数
            total: 0,// 数据总数
        }
    },
    //   页面初始化后执行
    created() {
        // this.flushPage();
        this.searchClick()
    },
    methods: {


        //富文本所需方法
        onEditorBlur() {
            //失去焦点事件
        },
        onEditorFocus() {
            //获得焦点事件
        },
        onEditorChange() {
            //内容改变事件
        },

        //移除文件
        handleRemove(file) {
            this.uploadImageList = this.uploadImageList.filter(item => item.name !== file.name);
            if (this.uploadImageList.length === 0) {
                this.form.picture = '';
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleDownload(file) {
            console.log(file);
        },
        //上传图片
        // uploadImg(r) {
        //     console.log(r.data);
        //     this.form.img = r.data
        // },

        uploadImg(response, file, fileList) {
            console.log(response);
            
            if (response.code === 200) {
                // 如果上传成功，将响应数据赋值给表单中的picture
                this.form.picture = response.data;
                //解决图片的闪动问题
                this.uploadImageList = fileList
                
            } else {
                this.$message.error('上传失败');
            }
        },


        save() {
            if (this.allId === -1) {   //allId为空 新增
                this.dialogFormVisible = false;
                this.axios.post("/free/add",
                    {
                        name: this.form.name,
                        picture: this.form.picture,
                        simplyintroduce: this.form.simplyintroduce,
                        text: this.form.text,
                        createtime: this.getCurrentDateTime()

                    }).then(res => {
                        console.log(res.data.data);
                        if (res.data.code == 200) {
                            this.$message.success("添加成功")
                        } else {
                            this.$message.error("添加失败")
                        }
                        this.clearForm();
                        this.flushPage();

                    })

            } else {      //allId不为空 修改
                // 编辑逻辑
                this.dialogFormVisible = false;

                this.axios.put("/free/update", {
                    id: this.form.id,
                    name: this.form.name,
                    picture: this.form.picture,
                    simplyintroduce: this.form.simplyintroduce,
                    text: this.form.text,
                    createtime: this.getCurrentDateTime()
                    // 如果需要更新创建时间，请添加 createtime 字段
                }).then(res => {
                    if (res.data.code == 200) {
                        this.$message.success("更新成功");
                    } else {
                        this.$message.error("更新失败");
                    }
                    this.clearForm();
                    this.flushPage();
                });
            }
        },
        //新增小区
        addXiaoqu() {
            this.dialogTitle = "新增公益信息";
            this.dialogFormVisible = true;
            this.clearForm()
            // this.isEditing = false;
            this.allId = -1;
        },
        //保存后清空表单
        clearForm() {

            this.form.name = "";
            this.form.picture = ''
            this.form.simplyintroduce = "";
            this.form.text = "";
            this.uploadImageList = [];
        },
        //格式化时间
        formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            // const hours = String(date.getHours()).padStart(2, '0');
            // const minutes = String(date.getMinutes()).padStart(2, '0');
            // const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        //取消
        cancel() {
            this.dialogFormVisible = false;
            this.uploadImageList = []; // 清空图片列表

        },

        //编辑
        editClick(row) {
            console.log(row.id);
            
            this.dialogTitle = "编辑公益信息";
            this.dialogFormVisible = true;
            this.row = row;
            this.allId = this.row.id;
            this.form = { ...row };  // 使用解构赋值复制整个对象,避免用户取消编辑，出现数据更改问题问题

            
            // 如果有图片，则为uploadImageList数组中的name和url属性进行赋值，图片回显
            if (row.picture) {
                this.uploadImageList = [{
                    name: row.picture,
                    url: `http://localhost:8080/free/download?filename=${row.picture}`
                }];
            } else {
                //如果没有图片，则把uploadImageList数组置空
                this.uploadImageList = [];
            }
        },

        //刷新页面获取数据
        flushPage() {
            this.axios.get("/free/selectAll",
                {
                    params: {
                        page: this.currentPage,
                        size: this.pageSize
                    }
                }
            ).then((res) => {
                console.log(res.data.data);
                this.tableData = res.data.data.list
                this.total = res.data.data.total
            }).catch(err => { console.log(err); })
        },
        //删除公益信息
        deleteClick(id) {

            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.axios.delete("/free/delete", {
                    params: {
                        id: id
                    }

                }).then((res) => {
                    console.log(res.data);
                    if (res.data.code == 200) {
                        this.$message.success("删除成功")
                    }
                    this.flushPage();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        //分页条件查询
        searchClick() {
            if (!this.searchContent.time) {
                this.searchContent.time = []
            }
            console.log(this.searchContent.name);
            console.log(this.currentPage);
            console.log(this.pageSize);
            console.log(this.searchContent.time[0] === undefined ? '' : this.formatDateTime(this.searchContent.time[0]));
            console.log(this.searchContent.time[1] === undefined ? '' : this.formatDateTime(this.searchContent.time[1]));

            this.axios.get('/free/selectByCondition',
                {
                    params: {
                        //传输的参数
                        title: this.searchContent.name,
                        page: this.currentPage,
                        size: this.pageSize,
                        startDate: this.searchContent.time[0] === undefined ? '' : this.formatDateTime(this.searchContent.time[0]),
                        endDate: this.searchContent.time[1] === undefined ? '' : this.formatDateTime(this.searchContent.time[1]),
                    }
                }
            ).then((res) => {
                //处理响应数据
                console.log(res);
                //真正需要的数据
                console.log(res.data.data.list);
                //将得到的数据加载到tableData
                this.tableData = res.data.data.list;
                //获取条件查询结果的总数
                this.total = res.data.data.total;
            }).catch(err => { })
        },

        // 切换每页显示条数
        handleSizeChange(size) {
            this.pageSize = size;
            // 可以在这里重新获取数据
            this.searchClick()
        },
        // 切换当前页
        handleCurrentChange(page) {
            console.log(page)
            this.currentPage = page;
            this.searchClick()

        },

        //获取当前系统日期并格式化为YYYY-MM-dd HH:mm:ss
        getCurrentDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = this.padNumber(now.getMonth() + 1);
            const day = this.padNumber(now.getDate());
            const hours = this.padNumber(now.getHours());
            const minutes = this.padNumber(now.getMinutes());
            const seconds = this.padNumber(now.getSeconds());
            return `${year}-${month}-${day}`;
        },
        padNumber(num) {
            return num < 10 ? '0' + num : num;
        }
    }
}
</script>


<style scoped>
.xiaoqu {
    height: 800px;
    /* background-color: hotpink; */
}

.xiaoqu-content {
    padding: 20px;
}

.searchBox {
    display: flex;
    justify-content: flex-start;
}

.searchLi {
    margin-right: 20px;
}

.addXiaoquBtn {
    margin-top: 20px;

}

input {
    height: 34px;
    outline: none;
    border: 1px solid #aaa;
    padding: 0 15px;
    border-radius: 5px;
}

input:hover {
    border: 1px solid #555555;
}

input:focus {
    border: 1px solid #409eff;
}

.addBtn {
    padding: 10px 20px;
    background-color: #409eff;
    color: whitesmoke;
    border: 1px solid #409eff;
}

.xiaoqu-table {
    margin-top: 20px;
    table-layout: auto;
}

.dialog-footer {
    margin-top: 40px;
}


</style>